package com.example.springboot03.controller;

import com.example.springboot03.domain.User;
import com.example.springboot03.repository.UserReposity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Optional;

@RestController
@RequestMapping("/users")
public class ThyController {
    @Autowired
    private UserReposity userReposity;
    

    @GetMapping
    public ModelAndView list(Model model){
        model.addAttribute("title","用户管理");
//        model.addAttribute("userList",userReposity.listUsers());
        model.addAttribute("userList",userReposity.findAll());
        return new ModelAndView("users/list","userModel",model);
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id,Model model){
//        User user = userReposity.getUserById(id);
        User user = userReposity.findById(id).get();
        model.addAttribute("user",user);
        model.addAttribute("title","查看用户");
        return new ModelAndView("users/view","userModel",model);
    }

    @GetMapping("/form")
    public ModelAndView createForm(Model model){
        model.addAttribute("user",new User(0,null,null));
        model.addAttribute("title","创建用户");
        return new ModelAndView("users/form","userModel",model);
    }

    @PostMapping
    public ModelAndView saveOrUpdateUser(User user){
//        user = userReposity.saveOrUpdate(user);
        user = userReposity.save(user);
        return new ModelAndView("redirect:/users"); //重定向到list页面
    }

    @GetMapping("/delete/{id}")
    public ModelAndView deleteUser(@PathVariable("id") Long id) {
        userReposity.deleteById(id);
        return new ModelAndView("redirect:/users");//重定向到list页面
    }

    @GetMapping("/modify/{id}")
    public ModelAndView modifyUser(@PathVariable("id") Long id,Model model){
//        model.addAttribute("user",userReposity.getUserById(id));
        model.addAttribute("user",userReposity.findById(id).get());
        model.addAttribute("title","修改用户");
        return new ModelAndView("users/modify","userModel",model);
    }


}
